/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.almac;

import dp1.titandevelop.titano.bean.Mensajes;
import dp1.titandevelop.titano.persistent.Almacen;
import dp1.titandevelop.titano.persistent.AlmacenXProducto;
import dp1.titandevelop.titano.persistent.Producto;
import dp1.titandevelop.titano.persistent.Zona;
import dp1.titandevelop.titano.service.AlmacenService;
import dp1.titandevelop.titano.service.AlmacenXProductoService;
import dp1.titandevelop.titano.service.ValidacionService;
import dp1.titandevelop.titano.service.ZonaService;
import java.awt.Cursor;
import java.awt.Frame;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Yulian
 */
public class ModulosT_ALM_AlmEdita extends javax.swing.JInternalFrame {


    private  List<Producto> productos ;
    private  List<Integer> idproductos;
    private  List<Integer> capacidades ;
    private  List<Zona> lista;
    
    private Mensajes sms = new Mensajes();
    
    private int idAlm;
    
    public void addProducto(Producto e){
        this.productos.add(e);
        this.idproductos.add(e.getIdproducto());
    }
    public void addCapacidad(int e){
        this.capacidades.add(e);
    }
    public void RefreshTable() {
        AbstractTableModel aux = (AbstractTableModel)tblCapacidades.getModel();
        aux.fireTableDataChanged();
    }
    public void habilitaBotones(){
        
        this.btnEliminar.setEnabled(true);
    }
    private void inhabilitaBotones(){
        this.btnEliminar.setEnabled(false);
    }
    private void addList (List<Zona> lista){
        
        for(int i=0;i<lista.size();i++){
            this.cboxZona.addItem(lista.get(i).getDescripcion());
        }
    } 
    private int findIndex (Almacen a,List<Zona> lista){
        int i=0;
        int idZona=a.getToZona().getIdzona();
        while(i<lista.size()){
            if (idZona==lista.get(i).getIdzona()) break;
            i++;
        }
        return (i+1);
    }
    private void rellenaProd_Cap(List<AlmacenXProducto> lista){
        int i = lista.size();
        for(int j=0;j<i;j++){
            Producto p = lista.get(j).getToProducto();
            this.addProducto(p);
            this.addCapacidad(lista.get(j).getCapacidad());
        }
    }
    private AbstractTableModel modeloTabla = new AbstractTableModel()  {  
        
        @Override
        public int getRowCount() {
            return capacidades.size(); // cuantos registros (filas)
        }      
        
        @Override
        public int getColumnCount() {
            return 2; // cuantas columnas
        }  
        
        String [] titles = {"Productos", "Capacidad"};
        
        @Override
        public String getColumnName(int col){
            return titles[col];
        }        
        @Override
        public boolean isCellEditable(int row, int column) {            
            return ( column == 1 );             
        }  
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object res=null;
            Producto prod = productos.get(rowIndex);
            Integer cap = capacidades.get(rowIndex);
            switch(columnIndex){
                case 0: res = prod.getDescripcion(); break;
                case 1: res = cap; break;
            }
            return res;
        }  
        
        @Override
        public void setValueAt(Object value, int row, int col) {
            if ( col == 1 ) {           
                capacidades.set(row, Integer.parseInt(""+value));
            }
            this.fireTableDataChanged();
        };
        
    };
    public ModulosT_ALM_AlmEdita() {
        initComponents();
    }

    ModulosT_ALM_AlmEdita(Almacen alm) {
        
        initComponents();
        idAlm = alm.getIdalmacen();
        this.productos=new ArrayList<Producto>();
        this.idproductos = new ArrayList<Integer>();
        this.capacidades = new ArrayList<Integer>();
                
        //Cbox con todas las zonas
        ZonaService servZ = new ZonaService();
        lista = servZ.buscar();
        addList(lista);        
        
        AlmacenXProductoService servA = new AlmacenXProductoService();
        List<AlmacenXProducto> listaProds = servA.buscarPorIdAlm(alm.getIdalmacen());
        
        int index = findIndex(alm,lista);
        
        this.txtDescripcion.setText(alm.getDescripcion());
        this.txtDireccion.setText(alm.getDireccion());
        this.cboxZona.setSelectedIndex(index);
        rellenaProd_Cap(listaProds);
        //Setear la tabla
        tblCapacidades.setModel(modeloTabla);
        this.inhabilitaBotones();        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        btnCancelar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblCapacidades = new javax.swing.JTable();
        btnEliminar = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtDescripcion = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtDireccion = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        cboxZona = new javax.swing.JComboBox();
        btnAsignar = new javax.swing.JButton();

        setResizable(true);
        setTitle("Editar Almacén");

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
        btnCancelar.setToolTipText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Registros de Capacidad"));
        jPanel2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jPanel2MouseClicked(evt);
            }
        });

        tblCapacidades.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Producto", "Capacidad"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Integer.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        tblCapacidades.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblCapacidadesMouseClicked(evt);
            }
        });
        tblCapacidades.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tblCapacidadesKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(tblCapacidades);

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/eliminar.png"))); // NOI18N
        btnEliminar.setToolTipText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8)
                .addComponent(btnEliminar)
                .addGap(8, 8, 8))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnEliminar)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8))
        );

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/grabar.png"))); // NOI18N
        btnGuardar.setToolTipText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del Almacén"));

        jLabel1.setText("Descripción");

        jLabel3.setText("Dirección");

        jLabel2.setText("Zona");

        cboxZona.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccionar" }));

        btnAsignar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/agregar.png"))); // NOI18N
        btnAsignar.setToolTipText("Asignar Producto");
        btnAsignar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAsignarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addGap(15, 15, 15)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtDescripcion)
                            .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(cboxZona, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnAsignar)))
                .addGap(8, 8, 8))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(15, 15, 15)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(15, 15, 15)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cboxZona, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(btnAsignar))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancelar))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addGap(8, 8, 8))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnGuardar)
                    .addComponent(btnCancelar))
                .addGap(8, 8, 8))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(1, 1, 1))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        ModulosT_ALM.menuAdmAlm.RefreshTable();
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void tblCapacidadesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblCapacidadesMouseClicked
        if(evt.getClickCount()==1){
            this.habilitaBotones();
        }
    }//GEN-LAST:event_tblCapacidadesMouseClicked

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        this.productos.remove(this.tblCapacidades.getSelectedRow());
        this.capacidades.remove(this.tblCapacidades.getSelectedRow());
        this.idproductos.remove(this.tblCapacidades.getSelectedRow());
        this.RefreshTable();
        this.inhabilitaBotones();
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed

         ValidacionService val = new ValidacionService();
         if(!val.esVacio(txtDescripcion)&&!val.esVacio(txtDireccion)&&!val.esCBoxVacio(cboxZona)){
            if(capacidades.size()>0){
                try {

                    AlmacenService serv = new AlmacenService();
                    
                    this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                    int ret= serv.editar(idAlm,lista.get(cboxZona.getSelectedIndex()-1).getIdzona(),txtDescripcion.getText(),txtDireccion.getText(),idproductos,capacidades);
                    this.setCursor(Cursor.getDefaultCursor());
                    
                    switch(ret){
                        case 1:JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getEditado(),"Mensaje",JOptionPane.INFORMATION_MESSAGE);break;
                        case 2:JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getNoEliminadoPorUso()+"\n"+sms.getNoEditadoPorUso(),"Aviso",JOptionPane.WARNING_MESSAGE);break;
                        case 3:JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getNoEditadoPorUso(),"Aviso",JOptionPane.WARNING_MESSAGE);break;
                        case 4:JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getNoEliminadoPorUso(),"Aviso",JOptionPane.WARNING_MESSAGE);break;
                        case 5:JOptionPane.showInternalMessageDialog(this.getRootPane(),"No se puede editar ya que la cantidad es menor al stock actual","Aviso",JOptionPane.WARNING_MESSAGE);
                    }

                } catch(Exception e) {
                    JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getError(),"Error",JOptionPane.ERROR_MESSAGE);
                }
                this.dispose();
            }
            else{
                JOptionPane.showInternalMessageDialog(this.getRootPane(), "Debe ingresar al menos un registro de capacidad.","Aviso",JOptionPane.WARNING_MESSAGE);
            }
        }
        else{
            JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getCompletarCampos(),"Aviso",JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnAsignarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAsignarActionPerformed
        Frame f = JOptionPane.getFrameForComponent(this);
        ModulosT_ALM_AlmNuevoAsignacion dialog = new ModulosT_ALM_AlmNuevoAsignacion(f,true);
        dialog.setVisible(true);

        //        ventanaAsignacion = new ModulosT_ALM_AlmNuevoAsig(productos,capacidades);
        //        this.getParent().add(ventanaAsignacion);
        //        ventanaAsignacion.setVisible(true);
    }//GEN-LAST:event_btnAsignarActionPerformed

    private void tblCapacidadesKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblCapacidadesKeyPressed

    }//GEN-LAST:event_tblCapacidadesKeyPressed

    private void jPanel2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel2MouseClicked

        this.RefreshTable();
        this.inhabilitaBotones();
    }//GEN-LAST:event_jPanel2MouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAsignar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JComboBox cboxZona;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblCapacidades;
    private javax.swing.JTextField txtDescripcion;
    private javax.swing.JTextField txtDireccion;
    // End of variables declaration//GEN-END:variables
}
